package com.knife.oauth.security.customer.entity;


import com.knife.oauth.domain.entity.IamPermission;
import com.knife.oauth.domain.entity.KnifeUserDetails;
import lombok.Data;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求上下文包装类
 *
 * @author tianhao.luo@hand-china.com
 * @version 1.0
 * @description
 * @date 2022/1/10 10:19 下午
 * @since 1.0
 */
@Data
public class RequestContext {

    private static final ThreadLocal<RequestContext> CONTEXT_THREAD_LOCAL = new ThreadLocal<>();
    /**
     * 校验请求包装类
     */
    public final CheckRequest request;
    /**
     * 校验结果包装类
     */
    public final CheckResponse response;

    private String requestKey;
    /**
     * 权限对象实体
     */
    private IamPermission permission;
    /**
     * uri
     */
    private String trueUri;
    /**
     * 当前用户信息
     */
    private KnifeUserDetails customUserDetails;
    /**
     * 当前请求的 servlet
     */
    private HttpServletRequest servletRequest;

    private HttpServletResponse servletResponse;
    /**
     * 菜单 id
     */
    private Long menuId;

    public RequestContext(CheckRequest request, CheckResponse builder, HttpServletRequest httpServletRequest, HttpServletResponse servletResponse) {
        this.request = request;
        this.response = builder;
        this.servletRequest = httpServletRequest;
        this.servletResponse = servletResponse;
    }

    public static RequestContext initRequestContext(CheckRequest request,
                                                    CheckResponse response,
                                                    HttpServletRequest httpServletRequest,
                                                    HttpServletResponse servletResponse) {
        RequestContext requestContext = new RequestContext(request, response, httpServletRequest, servletResponse);
        CONTEXT_THREAD_LOCAL.set(requestContext);
        return requestContext;
    }

    public static RequestContext currentRequestContext() {
        return CONTEXT_THREAD_LOCAL.get();
    }

    public static void clearRequestContext() {
        CONTEXT_THREAD_LOCAL.remove();
    }


}

